<template>
  <el-scrollbar class="h-full">
    <el-card>
      <!-- 机器人文件设置 -->
      <SettingItem title="机器人文件" description="上传和管理机器人文件，由管理员管理">
        <el-button type="primary" :icon="Plus" @click="showUploadDialog"> 上传文件 </el-button>
      </SettingItem>

      <!-- 机器人文件列表表格 -->
      <div class="mt-4">
        <el-table :data="robotFileList" stripe style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="fileName" label="文件名称" width="300" show-overflow-tooltip />
          <el-table-column prop="fileUrl" label="文件地址" min-width="400" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link :href="row.fileUrl" target="_blank" type="primary">{{
                row.fileUrl
              }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty v-if="!tableLoading && robotFileList.length === 0" description="暂无机器人文件" />
        <!-- 分页 -->
        <div class="flex justify-center mt-4">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 上传文件对话框 -->
    <el-dialog
      title="上传机器人文件"
      v-model="uploadDialogVisible"
      width="600px"
      destroy-on-close
      :before-close="handleCloseUploadDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">支持上传各种格式的机器人文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseUploadDialog">取消</el-button>
          <el-button
            type="primary"
            @click="handleUpload"
            :loading="uploadLoading"
            :disabled="!formData.file"
          >
            上传
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import SettingItem from '@/components/common/SettingItem.vue'
import { uploadRobotFile, fetchList, deleteRobotFile } from '@/api/roobotfile'
import { useUserStore } from '../../../store/user'

const userStore = useUserStore()

// 表格数据
const robotFileList = ref([])
const tableLoading = ref(false)
const uploadLoading = ref(false)

// 分页数据
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 对话框相关
const uploadDialogVisible = ref(false)
const formRef = ref()
const uploadRef = ref()

// 表单数据结构
const defaultForm = {
  file: null
}
const formData = ref({ ...defaultForm })
const fileList = ref([])

// 表单验证规则
const formRules = {
  file: [{ required: true, message: '请选择要上传的文件', trigger: 'change' }]
}

/**
 * 获取机器人文件列表
 */
const getRobotFileList = async () => {
  try {
    tableLoading.value = true
    const response = await fetchList({
      page: pagination.value.page,
      limit: pagination.value.limit
    })

    if (response.data?.list) {
      robotFileList.value = response.data.list
      pagination.value.total = response.data.total || 0
    } else {
      robotFileList.value = response.data || []
      pagination.value.total = robotFileList.value.length
    }
  } catch (error) {
    console.error('获取机器人文件列表失败:', error)
    ElMessage.error('获取机器人文件列表失败')
  } finally {
    tableLoading.value = false
  }
}

/**
 * 显示上传文件对话框
 */
const showUploadDialog = () => {
  formData.value = { ...defaultForm }
  fileList.value = []
  uploadDialogVisible.value = true
}

/**
 * 文件选择变化
 */
const handleFileChange = (file: any) => {
  formData.value.file = file.raw
}

/**
 * 文件移除
 */
const handleFileRemove = () => {
  formData.value.file = null
}

/**
 * 删除机器人文件
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除文件"${row.fileName}"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteRobotFile(row.id)
    ElMessage.success('删除成功')
    await getRobotFileList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 关闭上传对话框
 */
const handleCloseUploadDialog = () => {
  formData.value = { ...defaultForm }
  fileList.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
  uploadDialogVisible.value = false
}

/**
 * 上传文件
 */
const handleUpload = async () => {
  if (!formData.value.file) {
    ElMessage.error('请选择要上传的文件')
    return
  }

  try {
    uploadLoading.value = true

    const formDataToUpload = new FormData()
    formDataToUpload.append('file', formData.value.file)

    await uploadRobotFile(formDataToUpload)
    ElMessage.success('上传成功')

    handleCloseUploadDialog()
    await getRobotFileList()
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    uploadLoading.value = false
  }
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1
  getRobotFileList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  getRobotFileList()
}

// 组件挂载时获取数据
onMounted(() => {
  getRobotFileList()
})
</script>

<style scoped lang="scss">
.dialog-footer {
  @apply flex justify-end gap-2;
}

.el-table {
  margin-top: 16px;
}

.el-upload {
  width: 100%;
}
</style>
